UNPKG

@marko/translator-default

Version:
105 lines (93 loc) 2.72 kB
"use strict";exports.__esModule = true;exports.default = _default;var _babelUtils = require("@marko/babel-utils"); var _compiler = require("@marko/compiler"); var _util = require("../util"); function _default(path, attrs) { const len = attrs.length; if (len === 0) return _compiler.types.nullLiteral(); if (len === 1 && attrs[0].node.type === "MarkoSpreadAttribute") { return _compiler.types.callExpression( (0, _babelUtils.importDefault)( path.hub.file, "marko/src/runtime/vdom/helpers/attrs.js", "marko_attrs" ), [attrs[0].node.value] ); } if (attrs.some((attr) => attr.node.type === "MarkoSpreadAttribute")) { const attrsObjects = []; let props; for (let i = 0; i < len; i++) { const attr = attrs[i]; const { node: { name, value } } = attr; if (name) { const computed = (0, _util.evaluateAttr)(attr); const prop = _compiler.types.objectProperty( _compiler.types.stringLiteral(name), computed?.value !== undefined ? _compiler.types.stringLiteral(computed.value) : value ); if (props) { props.push(prop); } else { attrsObjects.push(_compiler.types.objectExpression(props = [prop])); } } else { attrsObjects.push(value); props = undefined; } } return _compiler.types.callExpression( (0, _babelUtils.importDefault)( path.hub.file, "marko/src/runtime/vdom/helpers/merge-attrs.js", "marko_merge_attrs" ), attrsObjects ); } const attrValues = new Map(); const props = []; // Remove duplicate attrs so last one wins. for (let i = len; i--;) { const attr = attrs[i]; const { name, value } = attr.node; if (attrValues.has(name)) continue; const computed = (0, _util.evaluateAttr)(attr); attrValues.set( name, computed ? { confident: true, computed: computed.value, value } : { confident: false, computed: undefined, value } ); } for (const [name, { confident, computed, value }] of [ ...attrValues]. reverse()) { if (confident) { if (computed == null || computed === false) { continue; } props.push( _compiler.types.objectProperty(_compiler.types.stringLiteral(name), _compiler.types.stringLiteral(computed)) ); } else { props.push(_compiler.types.objectProperty(_compiler.types.stringLiteral(name), value)); } } if (props.length) { return _compiler.types.objectExpression(props); } return _compiler.types.nullLiteral(); }